package com.nicy.molly.utils.interceptor;

import com.nicy.molly.utils.annotation.NeedLogin;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description: 登录拦截器
 * @projectName:molly
 * @see:com.nicy.molly.utils.interceptor
 * @author:NicyYe
 * @createTime:2021/2/22 14:42
 * @version:1.0
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    //验证登录状态的业务逻辑
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception{
       if(handler instanceof HandlerMethod){
           NeedLogin needLogin = ((HandlerMethod) handler).getMethodAnnotation(NeedLogin.class);
           if(null== needLogin){
               needLogin = ((HandlerMethod) handler).getMethod().getDeclaringClass().getAnnotation(NeedLogin.class);

           }

           //有登录验证注解，则校验登录
           if(null != needLogin){
               String token = (String)  request.getSession().getAttribute("token");
               //如果session中没有，表示登录
               if(null == token){
                   response.setCharacterEncoding("UTF-8");
                   response.getWriter().write("no login");
                   return false;
               }
           }
       }

       return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}
